package njiandan.mvc.render;

import java.io.PrintWriter;
import java.util.HashMap; 

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import njiandan.mvc.kit.JsonKit;

public class JsonRenderer extends Renderer { 
    private String characterEncoding;
    private String jsonText;
    private boolean forIE = false;
    private static int convertDepth = 8;
    
    public JsonRenderer forIE() {
		forIE = true;
		return this;
	}
    
    public JsonRenderer(String jsonText) {
        this.jsonText = jsonText;
    }

    public JsonRenderer(String jsonText, String characterEncoding) {
        this.jsonText = jsonText;
        this.characterEncoding = characterEncoding;
    }
    
    public JsonRenderer(Object object) {
		if (object == null)
			throw new IllegalArgumentException("The parameter object can not be null.");
		this.jsonText = JsonKit.toJson(object, convertDepth);
	}
    
	@SuppressWarnings("serial")
	public JsonRenderer(final String key, final Object value) {
		if (key == null)
			throw new IllegalArgumentException("The parameter key can not be null.");
		this.jsonText = JsonKit.toJson(new HashMap<String, Object>(){{put(key, value);}}, convertDepth);
	}
	
	
	public static void setConvertDepth(int convertDepth) {
		if (convertDepth < 2)
			throw new IllegalArgumentException("convert depth can not less than 2.");
		JsonRenderer.convertDepth = convertDepth;
	}

    @Override
    public void render(ServletContext context, HttpServletRequest request, HttpServletResponse response) throws Exception {
        StringBuilder sb = new StringBuilder(64);
        sb.append(contentType==null ? (forIE ?  "text/html" : "application/json") : contentType)
          .append(";charset=")
          .append(characterEncoding==null ? "UTF-8" : characterEncoding);
        response.setContentType(sb.toString());
        PrintWriter pw = response.getWriter();
        pw.write(jsonText);
        pw.flush();
    }
}
